package mybatis.io;

import mybatis.exception.MyBatisException;
import utils.LogUtils;

import java.io.InputStream;
import java.util.Objects;

/**
 * 类加载器包装类
 *
 * @author richie696
 * @version 1.0
 * @since 2020/11/07
 */
public class ClassLoaderWrapper {

//    private final ClassLoader systemClassLoader;

    ClassLoaderWrapper() {
        // 非Web项目暂时不用该加载器
//        systemClassLoader = ClassLoader.getSystemClassLoader();
    }

    /**
     * 根据指定资源获取其输入流对象的方法
     *
     * @param resource 资源路径
     * @return 返回资源的输入流对象
     */
    InputStream getResourceAsUrl(String resource) {
        InputStream resourceAsStream = ClassLoaderWrapper.class.getResourceAsStream(resource);
        if (Objects.isNull(resourceAsStream)) {
            resourceAsStream = ClassLoaderWrapper.class.getResourceAsStream("/" + resource);
        }
        if (Objects.isNull(resourceAsStream)) {
            String msg = String.format("资源路径：%s，下未找到指定文件。", resource);
            LogUtils.warn(msg);
            throw new MyBatisException(msg);
        }
        return resourceAsStream;
    }
}
